package com.our.sys.project1.web;

import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springside.modules.orm.Page;
import org.springside.modules.orm.PropertyFilter;

import com.our.sys.common.utils.AppUtil;
import com.our.sys.project1.entity.Businesslicence;
import com.our.sys.project1.entity.Medicallicenses;
import com.our.sys.project1.entity.Produclicenses;
import com.our.sys.project1.service.LicensesService;

@Controller
@RequestMapping("/licenses")
public class LicensesController {

    @Autowired
    private LicensesService licensesService;

    private static Logger logger = LoggerFactory.getLogger(LicensesController.class);

    @RequestMapping(value = "/query_m")
    public @ResponseBody
    Map<String, Object> queryM(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        Page<Medicallicenses> page = new Page<Medicallicenses>(request);
        String orderColumn = request.getParameter("sort");
        String dir = request.getParameter("dir");
        if (StringUtils.isBlank(orderColumn)) {
            page.setOrderBy("createTime");
            page.setOrder(Page.DESC);
        } else {
            page.setOrderBy(orderColumn);
            page.setOrder(dir);
        }

        List<PropertyFilter> filters = new ArrayList<PropertyFilter>();
        String supplier = request.getParameter("supplier");
        if (StringUtils.isNotBlank(supplier)) {
            PropertyFilter filter = new PropertyFilter("LIKES_supplier_OR_py_OR_wb", supplier.trim());
            filters.add(filter);
        }

        String highValueAllName = request.getParameter("highValueAllName");
        if (StringUtils.isNotBlank(highValueAllName)) {
            PropertyFilter filter = new PropertyFilter("LIKES_highValueAllName_OR_hapy_OR_hawb",
                    highValueAllName.trim());
            filters.add(filter);
        }

        String highValueItemName = request.getParameter("highValueItemName");
        if (StringUtils.isNotBlank(highValueItemName)) {
            PropertyFilter filter = new PropertyFilter("LIKES_highValueItemName_OR_hipy_OR_hiwb",
                    highValueItemName.trim());
            filters.add(filter);
        }

        String supplierId = request.getParameter("supplierId");
        PropertyFilter filter = new PropertyFilter("EQL_supplierId", StringUtils.isNotBlank(supplierId) ? supplierId
                : "");
        filters.add(filter);

        Page<Medicallicenses> data = licensesService.queryM(page, filters);
        map = AppUtil.buildJSONDataResponse(data.getResult(), (long) data.getTotalCount());
        return map;
    }

    @RequestMapping(value = "/query_b")
    public @ResponseBody
    Map<String, Object> queryB(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        Page<Businesslicence> page = new Page<Businesslicence>(request);
        String orderColumn = request.getParameter("sort");
        String dir = request.getParameter("dir");
        if (StringUtils.isBlank(orderColumn)) {
            page.setOrderBy("createTime");
            page.setOrder(Page.DESC);
        } else {
            page.setOrderBy(orderColumn);
            page.setOrder(dir);
        }

        List<PropertyFilter> filters = new ArrayList<PropertyFilter>();
        String supplier = request.getParameter("supplier");
        if (StringUtils.isNotBlank(supplier)) {
            PropertyFilter filter = new PropertyFilter("LIKES_supplier_OR_py_OR_wb", supplier.trim());
            filters.add(filter);
        }

        String supplierId = request.getParameter("supplierId");
        PropertyFilter filter = new PropertyFilter("EQL_supplierId", StringUtils.isNotBlank(supplierId) ? supplierId
                : "");
        filters.add(filter);

        Page<Businesslicence> data = licensesService.queryB(page, filters);
        map = AppUtil.buildJSONDataResponse(data.getResult(), (long) data.getTotalCount());
        return map;
    }

    @RequestMapping(value = "/query_p")
    public @ResponseBody
    Map<String, Object> queryP(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        Page<Produclicenses> page = new Page<Produclicenses>(request);
        String orderColumn = request.getParameter("sort");
        String dir = request.getParameter("dir");
        if (StringUtils.isBlank(orderColumn)) {
            page.setOrderBy("createTime");
            page.setOrder(Page.DESC);
        } else {
            page.setOrderBy(orderColumn);
            page.setOrder(dir);
        }

        List<PropertyFilter> filters = new ArrayList<PropertyFilter>();
        String supplier = request.getParameter("supplier");
        if (StringUtils.isNotBlank(supplier)) {
            PropertyFilter filter = new PropertyFilter("LIKES_supplier_OR_py_OR_wb", supplier.trim());
            filters.add(filter);
        }

        String supplierId = request.getParameter("supplierId");
        PropertyFilter filter = new PropertyFilter("EQL_supplierId", StringUtils.isNotBlank(supplierId) ? supplierId
                : "");
        filters.add(filter);

        Page<Produclicenses> data = licensesService.queryP(page, filters);
        map = AppUtil.buildJSONDataResponse(data.getResult(), (long) data.getTotalCount());
        return map;
    }

    @RequestMapping(value = "/save_m")
    public @ResponseBody
    Map<String, Object> saveM(Medicallicenses medicallicenses) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            licensesService.saveM(medicallicenses);
            map.put("success", true);
            map.put("message", "");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            map.put("success", false);
            map.put("message", e.getMessage());
        }
        return map;
    }

    @RequestMapping(value = "/save_b")
    public @ResponseBody
    Map<String, Object> saveB(Businesslicence businesslicence) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            licensesService.saveB(businesslicence);
            map.put("success", true);
            map.put("message", "");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            map.put("success", false);
            map.put("message", e.getMessage());
        }
        return map;
    }

    @RequestMapping(value = "/save_p")
    public @ResponseBody
    Map<String, Object> saveP(Produclicenses produclicenses) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            licensesService.saveP(produclicenses);
            map.put("success", true);
            map.put("message", "");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            map.put("success", false);
            map.put("message", e.getMessage());
        }
        return map;
    }

    @RequestMapping(value = "/delete_m")
    public @ResponseBody
    Map<String, Object> deleteM(@RequestParam("id") String id) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            licensesService.deleteM(Long.valueOf(id));
            map.put("success", true);
            map.put("message", "");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            map.put("success", false);
            map.put("message", e.getMessage());
        }
        return map;
    }

    @RequestMapping(value = "/delete_b")
    public @ResponseBody
    Map<String, Object> deleteB(@RequestParam("id") String id) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            licensesService.deleteB(Long.valueOf(id));
            map.put("success", true);
            map.put("message", "");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            map.put("success", false);
            map.put("message", e.getMessage());
        }
        return map;
    }

    @RequestMapping(value = "/delete")
    public @ResponseBody
    Map<String, Object> delete(@RequestParam("id") String id) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            licensesService.deleteP(Long.valueOf(id));
            map.put("success", true);
            map.put("message", "");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            map.put("success", false);
            map.put("message", e.getMessage());
        }
        return map;
    }

    @RequestMapping(value = "/save_img")
    public @ResponseBody
    Map<String, Object> saveImg(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            CommonsMultipartFile orginalFile = (CommonsMultipartFile) multipartRequest.getFile("userfile");
            String filename = String.valueOf(System.currentTimeMillis()) + "_" + orginalFile.getOriginalFilename();
            String clazzPath = request.getSession().getServletContext().getRealPath("/resources/img/upload");
            DataOutputStream out = new DataOutputStream(new FileOutputStream(clazzPath + "/" + filename));
            response.setContentType("text/html;charset=UTF-8");
            InputStream is = null;// 附件输入流
            try {
                is = orginalFile.getInputStream();
                byte[] b = new byte[is.available()];
                is.read(b);
                out.write(b);
                map.put("success", true);
                map.put("filePath", request.getContextPath()+"/resources/img/upload" + "/" + filename);
                map.put("message", "");
            } catch (IOException exception) {
                exception.printStackTrace();
            } finally {
                if (is != null) {
                    is.close();
                }
                if (out != null) {
                    out.close();
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            map.put("success", false);
            map.put("message", e.getMessage());
        }
        return map;
    }

    @RequestMapping(value = "/save_img_src_1")
    public @ResponseBody
    Map<String, Object> saveImgSrc1(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String id = request.getParameter("id");
        String filePath = request.getParameter("filePath");
        try {
            licensesService.saveImgSrcB(Long.valueOf(id), filePath);
            map.put("success", true);
            map.put("message", "");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            map.put("success", false);
            map.put("message", e.getMessage());
        }
        return map;
    }

    @RequestMapping(value = "/save_img_src_2")
    public @ResponseBody
    Map<String, Object> saveImgSrc2(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String id = request.getParameter("id");
        String filePath = request.getParameter("filePath");
        try {
            licensesService.saveImgSrcP(Long.valueOf(id), filePath);
            map.put("success", true);
            map.put("message", "");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            map.put("success", false);
            map.put("message", e.getMessage());
        }
        return map;
    }

    @RequestMapping(value = "/save_img_src_3")
    public @ResponseBody
    Map<String, Object> saveImgSrc3(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String id = request.getParameter("id");
        String filePath = request.getParameter("filePath");
        try {
            licensesService.saveImgSrcM(Long.valueOf(id), filePath);
            map.put("success", true);
            map.put("message", "");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            map.put("success", false);
            map.put("message", e.getMessage());
        }
        return map;
    }
}
